package com.fscut.springbootinit.aop;

import com.fscut.springbootinit.annotation.AuthCheck;
import com.fscut.springbootinit.exception.ErrorCode;
import com.fscut.springbootinit.exception.ThrowUtils;
import com.fscut.springbootinit.model.enums.UserRoleEnum;
import com.fscut.springbootinit.service.UserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 权限校验 AOP
 *
 */
@Aspect
@Component
public class AuthInterceptor {

    @Resource
    private UserService userService;

    /**
     * 对标记了AuthCheck注解的所有方法执行拦截，验证用户权限
     *
     */
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        //获取注解值
        String mustRole = authCheck.mustRole();

        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        // 获取当前登录用户的角色
        String userRole = userService.getLoginUser(request).getUserRole();
        // 必须有该权限才通过，注解值为空值直接放行不影响代码逻辑
        if (StringUtils.isNotBlank(mustRole)) {
            // 根据注解值尝试获取用户权限枚举
            UserRoleEnum mustUserRoleEnum = UserRoleEnum.getEnumByValue(mustRole);
            // 获取不到则表示用户权限枚举中不存在这个值，直接拒绝
            ThrowUtils.throwIf(mustUserRoleEnum == null, ErrorCode.NO_AUTH_ERROR);
            // 如果被封号，直接拒绝 (该方法不让任何人访问)
            ThrowUtils.throwIf(UserRoleEnum.BAN.equals(mustUserRoleEnum),ErrorCode.NO_AUTH_ERROR);
            // 如果注解值是ADMIN则表示方法需要管理员权限才可以访问，验证用户权限是否是管理员，不是则拒绝
            if (UserRoleEnum.ADMIN.equals(mustUserRoleEnum)) {
                ThrowUtils.throwIf(!mustRole.equals(userRole),ErrorCode.NO_AUTH_ERROR);
            }
        }
        // 通过权限校验，放行
        return joinPoint.proceed();
    }
}

